import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:macnov/common/macvon_button.dart';
import 'package:macnov/services/auth.dart';
import 'package:macnov/stores/signin.dart';
import 'package:macnov/utils/Api.dart';
import 'package:macnov/utils/constant.dart';
import 'package:passcode_screen/circle.dart';
import 'package:passcode_screen/keyboard.dart';
import 'package:passcode_screen/passcode_screen.dart';

class Login extends StatefulWidget {
  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {
  TextEditingController _phonecontroller = new TextEditingController();
  TextEditingController _pwdcontroller = new TextEditingController();
  final StreamController<bool> _verificationNotifier =
      StreamController<bool>.broadcast();

  bool isAuthenticated = false;

  String lockScreenPwd;
  @override
  void initState() {
    super.initState();
    this._loadLatestLoginOpt();
  }

  void _loadLatestLoginOpt() async {
    LoginOpt opt = await signInStore.loadLastLoginOption();
    if (signInStore.needAuth == false) return;
    if (opt == LoginOpt.TOUCHID) {
      this._authBiology();
    } else if (opt == LoginOpt.PIN) {
      _showLockScreen(context, opaque: true);
      lockScreenPwd = await signInStore.loadLastLoginPwd();
    } else {
      _showLastAccount(null);
    }
  }

  void _checkPhone() {
    if (_phonecontroller.text.isNotEmpty) {
    } else {}
  }

  void _authBiology() async {
    bool canCheckBiometrics = await authService.checkBiometrics();
    print("canCheckBiometrics $canCheckBiometrics");
    if (canCheckBiometrics) {
      bool authenticated = await authService.authenticate();
      if (authenticated) {
        _autoLogin();
      }
    }
  }

  void doLogin() {
    var email = signInStore.lastestUser;
    var pwd = signInStore.lastestPassword;
    _doLogin(email, pwd);
  }

  void _autoLogin() {
    _showLastAccount(doLogin);
  }

  void _signin() async {
    _checkPhone();
    _checkPwd();
    var email = _phonecontroller.text;
    var pwd = _pwdcontroller.text;
    _doLogin(email, pwd);
  }

  void _doLogin(email, pwd) async {
    var isOwner = await Api.doLogin({"username": '$email', "password": '$pwd'});
    if (isOwner == null) return;
    if (isOwner == true) {
      Navigator.pushReplacementNamed(context, '/owner');
    } else if (isOwner == false) {
      Navigator.pushReplacementNamed(context, '/employee');
    }
    signInStore.saveLastAccount(email, pwd);
  }

  void _showLastAccount(VoidCallback callabck) async {
    await signInStore.loadLastAccount();
    setState(() {
      _phonecontroller.text = signInStore.lastestUser;
      _pwdcontroller.text = signInStore.lastestPassword;
    });
    if (callabck != null) {
      callabck();
    }
  }

  void _checkPwd() {
    if (_pwdcontroller.text.isNotEmpty) {
    } else {}
  }

  void _showLockScreen(BuildContext context,
      {bool opaque,
      CircleUIConfig circleUIConfig,
      KeyboardUIConfig keyboardUIConfig}) {
    Navigator.push(
        context,
        PageRouteBuilder(
          opaque: opaque,
          pageBuilder: (context, animation, secondaryAnimation) =>
              PasscodeScreen(
            title: 'Enter App Passcode',
            circleUIConfig: circleUIConfig,
            keyboardUIConfig: keyboardUIConfig,
            passwordEnteredCallback: _onPasscodeEntered,
            passwordDigits: 4,
            cancelLocalizedText: 'Cancel',
            deleteLocalizedText: 'Delete',
            shouldTriggerVerification: _verificationNotifier.stream,
            backgroundColor: Colors.black.withOpacity(1.0),
            cancelCallback: _onPasscodeCancelled,
          ),
        ));
  }

  void _onPasscodeEntered(String enteredPasscode) {
    bool isValid = lockScreenPwd == enteredPasscode;
    _verificationNotifier.add(isValid);
    if (isValid) {
      _autoLogin();
    }
  }

  void _onPasscodeCancelled() {}

  @override
  void dispose() {
    _verificationNotifier.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark.copyWith(
      statusBarColor: Colors.white,
    ));
    return Scaffold(
      backgroundColor: Colors.white,
      body: ListView(
        children: <Widget>[
          Column(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Container(
                alignment: Alignment.topLeft,
                margin: new EdgeInsets.fromLTRB(0.0, 30.0, 0.0, 0.0),
                padding: new EdgeInsets.fromLTRB(20.0, 0.0, 20.0, 15.0),
                child: new Image.asset(
                  'assets/pics/bank_zs11.png',
                  width: 40.0,
                  height: 40.0,
                ),
              ),
              Container(
                  alignment: Alignment.topLeft,
                  margin: new EdgeInsets.fromLTRB(0.0, 40.0, 0.0, 0.0),
                  padding: new EdgeInsets.fromLTRB(20.0, 0.0, 20.0, 0.0),
                  child: new Text(
                    'Welcome to,',
                    textAlign: TextAlign.left,
                    style: TextStyle(
                      fontSize: 38,
                      fontWeight: FontWeight.bold,
                    ),
                  )),
              Container(
                alignment: Alignment.topLeft,
                padding: new EdgeInsets.fromLTRB(20.0, 0.0, 20.0, 15.0),
                margin: new EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 40.0),
                child: new Text('Macnov',
                    textAlign: TextAlign.left,
                    style:
                        TextStyle(fontSize: 38, fontWeight: FontWeight.bold)),
              ),
              new Padding(
                padding: new EdgeInsets.fromLTRB(20.0, 0.0, 20.0, 15.0),
                child: new Stack(
                  alignment: new Alignment(1.0, 1.0),
                  //statck
                  children: <Widget>[
                    new Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          new Expanded(
                            child: new TextField(
                              controller: _phonecontroller,
                              decoration: new InputDecoration(
                                hintText: 'Email',
                              ),
                            ),
                          ),
                        ]),
                  ],
                ),
              ),
              new Padding(
                padding: new EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 40.0),
                child: new Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      new Expanded(
                        child: new TextField(
                          controller: _pwdcontroller,
                          keyboardType: TextInputType.visiblePassword,
                          decoration: new InputDecoration(
                            hintText: 'Password',
                          ),
                          obscureText: true,
                        ),
                      ),
                    ]),
              ),
              new Container(
                margin: EdgeInsets.fromLTRB(20, 20, 20, 0),
                child: GradientButton(
                  onTap: this._signin,
                  child: new Text(
                    'SIGN IN',
                    style: new TextStyle(color: Colors.white, fontSize: 16.0),
                  ),
                ),
              )
            ],
          ),
        ],
      ),
    );
  }
}
